//
//  RepairEstimateView.m
//  HondaPro_2
//
//  Created by Eric on 13-6-3.
//  Copyright (c) 2013年 glendale. All rights reserved.
//

#import "RepairEstimateView.h"
#import "MainMenuDataModel.h"
#import "UserDefinedCellForRepairEstimateView.h"

@interface RepairEstimateView ()

//添加控件
-(void)initSelectedRect;
-(void)createStaticImage;
-(void)createLabels;
-(void)createTableViews;

//刷新控件内容
-(void)freshenViewDis;

//传入的下标的引用，和tableView的行数，以更新下标的值
-(void)updateTheIndex:(NSInteger &)firstIndex andSecondIndex:(NSInteger &)secondIndex andCurrRow:(NSInteger)row;

@end

@implementation RepairEstimateView

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
        
        [self initSelectedRect];
        [self createStaticImage];
        [self createTableViews];
        [self createLabels];
    }
    return self;
}

// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
    // Drawing code
    [self freshenViewDis];
}

#pragma mark - 添加控件

-(void)initSelectedRect
{
    dicForSelected = [NSDictionary dictionaryWithObjectsAndKeys:
                      [NSValue valueWithCGRect:CGRectMake(6, 15, 20, 20)],@"保修",
                      [NSValue valueWithCGRect:CGRectMake(62, 15, 20, 20)],@"返修",
                      [NSValue valueWithCGRect:CGRectMake(122, 15, 20, 20)],@"快修",
                      [NSValue valueWithCGRect:CGRectMake(184, 15, 20, 20)],@"多客户结算",
                      [NSValue valueWithCGRect:CGRectMake(273, 15, 20, 20)],@"二手车翻新",
                      [NSValue valueWithCGRect:CGRectMake(424, 15, 20, 20)],@"首保",
                      [NSValue valueWithCGRect:CGRectMake(484, 15, 20, 20)],@"年检保养",
                      [NSValue valueWithCGRect:CGRectMake(566, 15, 20, 20)],@"喷漆",
                      [NSValue valueWithCGRect:CGRectMake(618, 15, 20, 20)],@"定期保养",
                      [NSValue valueWithCGRect:CGRectMake(687, 15, 20, 20)],@"钣金",
                      [NSValue valueWithCGRect:CGRectMake(736, 15, 20, 20)],@"一般修理",
                      [NSValue valueWithCGRect:CGRectMake(810, 15, 20, 20)],@"精品", nil];
}

-(void)createStaticImage
{
    //table view title imageView
//    UIImage *img2 = [UIImage imageNamed:@"image2.png"];
//    UIImageView *imgView2 = [[UIImageView alloc] initWithImage:img2];
//    imgView2.frame = CGRectMake(30, 90, self.frame.size.width-60, 30);
//    [self addSubview:imgView2];
    
    //添加表单的标题栏
    UILabel *lblBottom = [self createAnStaticLblByFrame:CGRectMake(30, 90, self.frame.size.width-60, 50) withTxt:@"" andBackgroundColor:[UIColor colorWithRed:0.96 green:0.96 blue:0.96 alpha:1]];
    [lblBottom addSubview:[self createAnStaticLblByFrame:CGRectMake(0, 0, 92, 50) withTxt:@"    描述号" andBackgroundColor:[UIColor clearColor]]];
    [lblBottom addSubview:[self createAnStaticLblByFrame:CGRectMake(94, 0, 257, 50) withTxt:@"陈述内容" andBackgroundColor:[UIColor clearColor]]];
    [lblBottom addSubview:[self createAnStaticLblByFrame:CGRectMake(352, 0, 106, 50) withTxt:@"陈述号" andBackgroundColor:[UIColor clearColor]]];
    [lblBottom addSubview:[self createAnStaticLblByFrame:CGRectMake(459, 0, 101, 50) withTxt:@"作业号" andBackgroundColor:[UIColor clearColor]]];
    [lblBottom addSubview:[self createAnStaticLblByFrame:CGRectMake(561, 0, 316, 50) withTxt:@"作业内容" andBackgroundColor:[UIColor clearColor]]];
    
    [self addSubview:lblBottom];
}

-(void)createLabels
{
    UIView *view1 = [[UIView alloc] initWithFrame:CGRectMake(30, 275+50, self.frame.size.width-60, 180-60)];
    view1.backgroundColor = [UIColor lightGrayColor];
    
    UIView *view2 = [[UIView alloc] initWithFrame:CGRectMake(1, 1, view1.frame.size.width-2, view1.frame.size.height-2)];
    view2.backgroundColor = [UIColor whiteColor];
    [view1 addSubview:view2];
    
    [self addSubview:view1];
    
    //创建labels
    label1 = [[UILabel alloc] initWithFrame:CGRectMake(10, 10, 240, 100)];
    label1.backgroundColor = [UIColor clearColor];
    label1.numberOfLines = 4;
    label1.font = [UIFont systemFontOfSize:13];
    label1.textColor = [UIColor darkGrayColor];
    [view2 addSubview:label1];
    
    label2 = [[UILabel alloc] initWithFrame:CGRectMake(260, 10, 240, 100)];
    label2.backgroundColor = [UIColor clearColor];
    label2.numberOfLines = 4;
    label2.font = [UIFont systemFontOfSize:13];
    label2.textColor = [UIColor darkGrayColor];
    [view2 addSubview:label2];

    label3 = [[UILabel alloc] initWithFrame:CGRectMake(510, 10, 350, 100)];
    label3.backgroundColor = [UIColor clearColor];
    label3.numberOfLines = 4;
    label3.font = [UIFont systemFontOfSize:13];
    label3.textColor = [UIColor darkGrayColor];
    [view2 addSubview:label3];
}

-(void)createTableViews
{
    tableViewDis = [[UITableView alloc] initWithFrame:CGRectMake(30, 120+30-10, self.frame.size.width-60, 150)];
    
    tableViewDis.delegate = self;
    tableViewDis.dataSource = self;
    
    tableViewDis.backgroundColor = [UIColor clearColor];
    
    [self addSubview:tableViewDis];
}

//刷新控件内容
-(void)freshenViewDis
{
    MainMenuDataModel *modelIns = [MainMenuDataModel sharedMainMenuDataModel];
    NSDictionary *dic = modelIns.repairEstimate;
    
    //更新显示图标
//    selImgView1.frame = [[dicForSelected objectForKey:[dic objectForKey:@"serviceTypeName"]] CGRectValue];
//    selImgView2.frame = [[dicForSelected objectForKey:[dic objectForKey:@"repairTypeName"]] CGRectValue];
    [self createSeveralIconOnStaticImg];
    
    //重新加载tableView的数据
    [tableViewDis reloadData];
    
    //更新label的值
    label1.text = [NSString stringWithFormat:@"预算费用：%@\n自厂工时：%@\n首次估价金额：%@\n当前估价金额：%@",
                   [dic objectForKey:@"budgetCharge"],
                   [dic objectForKey:@"customWorkHour"],
                   [dic objectForKey:@"firstEvaluatorMoney"],
                   [dic objectForKey:@"currentEvaluatorMoney"]];
    
    label2.text = [NSString stringWithFormat:@"其它费用：%@\n预交款：%@\n估价人：%@\n估价日期：%@",
                   [dic objectForKey:@"otherCharge"],
                   [dic objectForKey:@"advancePayment"],
                   [dic objectForKey:@"evaluator"],
                   [dic objectForKey:@"evaluatorDate"]];
    
    label3.text = [NSString stringWithFormat:@"预算完工日：%@\n实际完工日：%@\n预算交车日：%@\n实际交车日：%@",
                   [dic objectForKey:@"expectedCompleteDate"],
                   [dic objectForKey:@"completeDate"],
                   [dic objectForKey:@"expecteddeliveryDate"],
                   [dic objectForKey:@"deliveryDate"]];
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    MainMenuDataModel *ins = [MainMenuDataModel sharedMainMenuDataModel];
    NSArray *arr = [ins.repairEstimate objectForKey:@"results"];
    
    rowSum = 0;
    
    for (int i = 0; i<[arr count]; i++)
    {
        NSArray *arrSub = [[arr objectAtIndex:i] objectForKey:@"indicationList"];
        for (int j = 0; j<[arrSub count]; j++)
        {
            ++rowSum;
        }
    }
    
    return 3+rowSum;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    UserDefinedCellForRepairEstimateView *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil)
    {
        cell = [[UserDefinedCellForRepairEstimateView alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }
    
    // Configure the cell...
    
    NSInteger row = [indexPath row];
    MainMenuDataModel *ins = [MainMenuDataModel sharedMainMenuDataModel];
    NSArray *arr = [ins.repairEstimate objectForKey:@"results"];
    
    //cell的风格是：浅浅灰色和浅灰色间隔出现，第一行是浅灰色
    switch (row%2)
    {
        case 0:
            //浅灰色
            cell.contentView.backgroundColor = [UIColor colorWithRed:0.9 green:0.9 blue:0.9 alpha:1];
            break;
        case 1:
            //浅浅灰色
            cell.contentView.backgroundColor = [UIColor colorWithRed:0.98 green:0.98 blue:0.98 alpha:1];
            break;
            
        default:
            break;
    }
    
    if (row < rowSum)
    {
        if (row < [arr count])
        {
            cell.label1.text = [[arr objectAtIndex:row] objectForKey:@"statementNumber"];
            cell.label2.text = [[arr objectAtIndex:row] objectForKey:@"stateContent"];
        }
        else
        {
            cell.label1.text = @"";
            cell.label2.text = @"";
        }
        
        NSInteger i = 0,j = 0;
        [self updateTheIndex:i andSecondIndex:j andCurrRow:row];
        cell.label3.text = [[arr objectAtIndex:i] objectForKey:@"statementNumber"];
        NSArray *arrSub = [[arr objectAtIndex:i] objectForKey:@"indicationList"];
        cell.label4.text = [[arrSub objectAtIndex:j] objectForKey:@"indicationNumber"];
        cell.label5.text = [[arrSub objectAtIndex:j] objectForKey:@"indicationContent"];
    }
    else
    {
        cell.label1.text = cell.label2.text = cell.label3.text = cell.label4.text = cell.label5.text = @"";
    }
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 50;
}

/*
 // Override to support conditional editing of the table view.
 - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
 {
 // Return NO if you do not want the specified item to be editable.
 return YES;
 }
 */

/*
 // Override to support editing the table view.
 - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
 {
 if (editingStyle == UITableViewCellEditingStyleDelete) {
 // Delete the row from the data source
 [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
 }
 else if (editingStyle == UITableViewCellEditingStyleInsert) {
 // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
 }
 }
 */

/*
 // Override to support rearranging the table view.
 - (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
 {
 }
 */

/*
 // Override to support conditional rearranging of the table view.
 - (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
 {
 // Return NO if you do not want the item to be re-orderable.
 return YES;
 }
 */

#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Navigation logic may go here. Create and push another view controller.
    /*
     <#DetailViewController#> *detailViewController = [[<#DetailViewController#> alloc] initWithNibName:@"<#Nib name#>" bundle:nil];
     // ...
     // Pass the selected object to the new view controller.
     [self.navigationController pushViewController:detailViewController animated:YES];
     */
}

#pragma mark - 传入的下标的引用，和tableView的行数，以更新下标的值

-(void)updateTheIndex:(NSInteger &)firstIndex andSecondIndex:(NSInteger &)secondIndex andCurrRow:(NSInteger)rowIndex
{
    int nNum = 0;
    MainMenuDataModel *ins = [MainMenuDataModel sharedMainMenuDataModel];
    NSArray *arr = [ins.repairEstimate objectForKey:@"results"];
    for (int i = 0; i<[arr count]; i++)
    {
        NSArray *arrSub = [[arr objectAtIndex:i] objectForKey:@"indicationList"];
        nNum += [arrSub count];
        if (rowIndex < nNum)
        {
            firstIndex = i;
            int nTmp = 0;
            for (int j = 0; j<i; j++)
            {
                nTmp += [[[arr objectAtIndex:j] objectForKey:@"indicationList"] count];
            }
            secondIndex = rowIndex-nTmp;
            return;
        }
    }
}

//创建一个静态lbl
-(UILabel *)createAnStaticLblByFrame:(CGRect)xingCanRect withTxt:(NSString *)strTxt andBackgroundColor:(UIColor *)bgColor
{
    UILabel *lbl = [[UILabel alloc] initWithFrame:xingCanRect];
    lbl.backgroundColor = bgColor;
    lbl.font = [UIFont systemFontOfSize:13];
    lbl.textColor = [UIColor darkGrayColor];
    lbl.text = strTxt;
    
    return lbl;
}

//放置小图标
-(void)createSeveralIconOnStaticImg
{
//    //selected imageView
//    UIImage *img1 = [UIImage imageNamed:@"image1.png"];
//    UIImageView *imgView1 = [[UIImageView alloc] initWithImage:img1];
//    imgView1.frame = CGRectMake(30, 20, self.frame.size.width-60, 50);
//    [self addSubview:imgView1];
//
//    MainMenuDataModel *modelIns = [MainMenuDataModel sharedMainMenuDataModel];
//    NSDictionary *dic = modelIns.repairEstimate;
//    
//    //放置小图标
//    UIImage *selImg1 = [UIImage imageNamed:@"对号.png"];
//    selImgView1 = [[UIImageView alloc] initWithImage:selImg1];
//    selImgView1.frame = [[dicForSelected objectForKey:[dic objectForKey:@"serviceTypeName"]] CGRectValue];
//    [imgView1 addSubview:selImgView1];
//
//    UIImage *selImg2 = [UIImage imageNamed:@"对号.png"];
//    selImgView2 = [[UIImageView alloc] initWithImage:selImg2];
//    selImgView2.frame = [[dicForSelected objectForKey:[dic objectForKey:@"repairTypeName"]] CGRectValue];
//    [imgView1 addSubview:selImgView2];
    
//    dicForSelected = [NSDictionary dictionaryWithObjectsAndKeys:
//                      [NSValue valueWithCGRect:CGRectMake(6, 15, 20, 20)],@"保修",
//                      [NSValue valueWithCGRect:CGRectMake(62, 15, 20, 20)],@"返修",
//                      [NSValue valueWithCGRect:CGRectMake(122, 15, 20, 20)],@"快修",
//                      [NSValue valueWithCGRect:CGRectMake(184, 15, 20, 20)],@"多客户结算",
//                      [NSValue valueWithCGRect:CGRectMake(273, 15, 20, 20)],@"二手车翻新",
//                      [NSValue valueWithCGRect:CGRectMake(424, 15, 20, 20)],@"首保",
//                      [NSValue valueWithCGRect:CGRectMake(484, 15, 20, 20)],@"年检保养",
//                      [NSValue valueWithCGRect:CGRectMake(566, 15, 20, 20)],@"喷漆",
//                      [NSValue valueWithCGRect:CGRectMake(618, 15, 20, 20)],@"定期保养",
//                      [NSValue valueWithCGRect:CGRectMake(687, 15, 20, 20)],@"钣金",
//                      [NSValue valueWithCGRect:CGRectMake(736, 15, 20, 20)],@"一般修理",
//                      [NSValue valueWithCGRect:CGRectMake(810, 15, 20, 20)],@"精品", nil];
    
    //（1）移除服务类型和维修分类的视图
    [_imgViewServiceAndRepairType removeFromSuperview];
    
    //（2）创建服务类型和维修分类的视图并添加到本类对应的视图上
    UIImage *img1 = [UIImage imageNamed:@"image1.png"];
    _imgViewServiceAndRepairType = [[UIImageView alloc] initWithImage:img1];
    _imgViewServiceAndRepairType.frame = CGRectMake(30, 20, self.frame.size.width-60, 50);
    [self addSubview:_imgViewServiceAndRepairType];
    
    //（3）放置icon
    for (int i = 0; i<[[dicForSelected allKeys] count]; i++)
    {
        MainMenuDataModel *modelIns = [MainMenuDataModel sharedMainMenuDataModel];
        NSDictionary *dic = modelIns.repairEstimate;
        NSString *strTmp = [dic objectForKey:@"serviceTypeName"];
        
        if ([strTmp rangeOfString:@"保修"].length == 2)
        {
            [self addAnimgViewOnStaticImgByCgrect:[[dicForSelected objectForKey:@"保修"] CGRectValue]];
        }
        if ([strTmp rangeOfString:@"返修"].length == 2)
        {
            [self addAnimgViewOnStaticImgByCgrect:[[dicForSelected objectForKey:@"返修"] CGRectValue]];
        }
        if ([strTmp rangeOfString:@"快修"].length == 2)
        {
            [self addAnimgViewOnStaticImgByCgrect:[[dicForSelected objectForKey:@"快修"] CGRectValue]];
        }
        if ([strTmp rangeOfString:@"多客户结算"].length == 5)
        {
            [self addAnimgViewOnStaticImgByCgrect:[[dicForSelected objectForKey:@"多客户结算"] CGRectValue]];
        }
        if ([strTmp rangeOfString:@"二手车翻新"].length == 5)
        {
            [self addAnimgViewOnStaticImgByCgrect:[[dicForSelected objectForKey:@"二手车翻新"] CGRectValue]];
        }
        
        strTmp = [dic objectForKey:@"repairTypeName"];
        if ([strTmp rangeOfString:@"首保"].length == 2)
        {
            [self addAnimgViewOnStaticImgByCgrect:[[dicForSelected objectForKey:@"首保"] CGRectValue]];
        }
        if ([strTmp rangeOfString:@"年检保养"].length == 4)
        {
            [self addAnimgViewOnStaticImgByCgrect:[[dicForSelected objectForKey:@"年检保养"] CGRectValue]];
        }
        if ([strTmp rangeOfString:@"喷漆"].length == 2)
        {
            [self addAnimgViewOnStaticImgByCgrect:[[dicForSelected objectForKey:@"喷漆"] CGRectValue]];
        }
        if ([strTmp rangeOfString:@"定期保养"].length == 4)
        {
            [self addAnimgViewOnStaticImgByCgrect:[[dicForSelected objectForKey:@"定期保养"] CGRectValue]];
        }
        if ([strTmp rangeOfString:@"钣金"].length == 2)
        {
            [self addAnimgViewOnStaticImgByCgrect:[[dicForSelected objectForKey:@"钣金"] CGRectValue]];
        }
        if ([strTmp rangeOfString:@"一般修理"].length == 4)
        {
            [self addAnimgViewOnStaticImgByCgrect:[[dicForSelected objectForKey:@"一般修理"] CGRectValue]];
        }
        if ([strTmp rangeOfString:@"精品"].length == 2)
        {
            [self addAnimgViewOnStaticImgByCgrect:[[dicForSelected objectForKey:@"精品"] CGRectValue]];
        }
    }
}

//给 _imgViewServiceAndRepairType 视图上添加子视图
-(void)addAnimgViewOnStaticImgByCgrect:(CGRect)rect
{
    UIImage *selImg1 = [UIImage imageNamed:@"对号.png"];
    selImgView1 = [[UIImageView alloc] initWithImage:selImg1];
    selImgView1.frame = rect;
    [_imgViewServiceAndRepairType addSubview:selImgView1];
}

@end
